-module(id_mgr).
-export([init_uid_index/0,gen_new_uid/0]).
-export([gen_new_scene_id/0,gen_new_team_id/0]).

-include("log.hrl").


init_uid_index() ->
	Min = server_tools:get_server_id() * 1000000,
	Max = (server_tools:get_server_id()+1) * 1000000,
	Sql = io_lib:format("SELECT MAX(id) FROM usr WHERE id>=~p and id<~p", [Min,Max]),
	Index = 
	case dbm_worker:work({run, Sql}) of
		{ok, [[undefined]]} -> 1;
		{ok, [[Index1]]} when is_integer(Index1) -> Index1+1;
		Other ->
			?log_warning("init uid index failed,ret=~p",[Other]),
			1
	end,
	db:set_sql_max_id(usr,Index).

gen_new_uid() ->
	%% uid = server_id*1000000 + index
	%% uid为uint32,最大不能超过4294967295,server_id不能超过4294,单服角色数不能超过967295
	case db:get_sql_new_id(usr) of
		Id when is_integer(Id) ->
			Index = Id rem 1000000,
			if
				Index >= 967295 ->
					?log_warning("gen_new_uid failed,index upon limit"),
					false;
				true -> {ok, server_tools:get_server_id() * 1000000 + Index}
			end;
		_ ->
			false
	end.

gen_new_scene_id() ->
	NextId = 
	case get(next_scene_id) of
		Id when is_integer(Id) -> Id;
		_ -> 1
	end,
	put(next_scene_id, NextId+1),
	NextId.

gen_new_team_id()->
	db:get_sql_new_id(sys_team).
